﻿using System;
using System.Windows.Input;

namespace theeg.DependencyAnalysis.CommonAddin.Behaviors
{
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        public string Name { get; set; }

        public Key Key { get; set; }

        public ModifierKeys ModifierKeys { get; set; }

        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute == null) return;
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (_canExecute == null) return;
                CommandManager.RequerySuggested -= value;
            }
        }

        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        public RelayCommand Clone(Action<object> execute, Predicate<object> canExecute)
        {
            return new RelayCommand(execute, canExecute) { Key = Key, ModifierKeys = ModifierKeys, Name = Name };
        }
    }
}